package com.yang.sso.oauth2.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Map;

/**
 * Oauth2端点工具类
 * @author: lslands
 * @version: 1.0
 * @create: 2024/5/12
 * @description:
 */
public class OAuth2EndpointUtils {


    public static final String ACCESS_TOKEN_REQUEST_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";


    /**
     * @param request 入参
     * @return MultiValueMap<String,String>
     * @author lslands
     * @date 2024/5/12 16:31
     */
    public static MultiValueMap<String, String> getParameters(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size());
        parameterMap.forEach((key, values) -> {
            if (values.length > 0) {
                for (String value : values) {
                    parameters.add(key, value);
                }
            }
        });
        return parameters;
    }


    /**
     * @param errorCode 错误码
     * @param parameterName 参数名称
     * @param errorUri 异常回调地址
     * @author lslands
     * @date 2024/5/12 16:40
     */
    public static void throwError(String errorCode, String parameterName, String errorUri) {
        OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.1 Parameter: " + parameterName, errorUri);
        throw new OAuth2AuthenticationException(error);
    }
}
